package video;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serializable;
import utils.PicUtils;

public class Flash implements Serializable {

    transient BufferedImage image;
    String asciiImage;
    static int size = 100;
    int id;

    public Flash(BufferedImage image, int id) throws IOException {
        this.id = id;
        this.image = image;
        this.asciiImage = createAsciiPic(image, new StringBuffer()).toString();
    }

    public String getAsciiImage() {
        return asciiImage;
    }

    public static StringBuffer createAsciiPic(BufferedImage image, StringBuffer ans) throws IOException {
        // 压缩图片
        BufferedImage bufferedImage = PicUtils.compressPic(image, 100, 0.8, 1920, 1080);
//        BufferedImage bufferedImage = compressImage(image);
        final String base = "¥$€£₩¢%*~;:,^`'.";
        int height = bufferedImage.getHeight();
        int width = bufferedImage.getWidth();
        for (int y = 0; y < height; y +=2) {
            for (int x = 0; x < width; x++) {
                final int pixel = bufferedImage.getRGB(x, y);
                final int red = (pixel & 0xff0000) >> 16, green = (pixel & 0xff00) >> 8, blue = pixel & 0xff;
                final float gray = 0.299f * red + 0.587f * green + 0.114f * blue;
                int index = Math.round(gray * (base.length() + 1) / 255);
                ans.append(index >= base.length() ? " " : String.valueOf(base.charAt(index)));
            }
            ans.append("\r\n");
        }
        return ans;
    }

    public static BufferedImage compressImage(BufferedImage srcImg) {
        int h = srcImg.getHeight();
        int w = srcImg.getWidth();
        if (Math.max(h, w) <= size) {
            return srcImg;
        }
        int new_H;
        int new_W;
        if (w > h) {
            new_W = size;
            new_H = size * h / w;
        } else {
            new_H = size;
            new_W = size * w / h;
        }
        BufferedImage smallImg = new BufferedImage(new_W, new_H, srcImg.getType());
        Graphics g = smallImg.getGraphics();
        g.drawImage(srcImg, 0, 0, new_W, new_H, null);
        g.dispose();
        return smallImg;
    }

}



